//============================================================================
// Name        : cpp_icu_charset.cpp
// Author      : darkflash
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <unicode/ucsdet.h>
#include <iconv.h>
#include <cerrno>
using namespace std;

int main() {
	UCharsetDetector* det;
	const UCharsetMatch* match;
	const char* charset;
	UErrorCode err;
	char errBuffer[1024];
	int i, num;

	string str = "가나";
	char *buffer = new char[str.length()+1];
	strcpy(buffer, str.c_str());

	err = U_ZERO_ERROR;
	det = ucsdet_open(&err);
//	if(U_FAILURE(err))
//		        fprintf( stderr, "Error in open" );

	ucsdet_setText(det, buffer, strlen(buffer), &err);
//	if(U_FAILURE(err))
//		fprintf( stderr, "Error in set text" );

	//match = ucsdet_detectAll(det, &num, &err);
	match = ucsdet_detect(det, &err);

//	if(U_FAILURE(err))
//		fprintf( stderr, "Error in detect" );

	charset = ucsdet_getName(match, &err);
//	if(U_FAILURE(err))
//				fprintf( stderr, "Error in getName" );

	cout << str << ": " << charset << endl;

	// UTF-8 to EUC-KR
	iconv_t cd = iconv_open( "EUC-KR", "UTF-8" );
	char encodeBuffer[1024] = {'\0', };

	size_t nsLen = strlen(buffer);
	size_t nwLen = sizeof(encodeBuffer);

	char* encodeBufferPtr = encodeBuffer;

	if( cd != (iconv_t)(-1) ){
		int ret = iconv( cd, &buffer, &nsLen, &encodeBufferPtr, &nwLen );

		if (ret < 0)
		{
			strerror_r(errno, errBuffer, sizeof(errBuffer) );
			printf("ret : %d, errno : %d(%s)\n", ret, errno,errBuffer);
			return(-1);
		}
		else
		{
			ucsdet_setText(det, encodeBuffer, strlen(encodeBuffer), &err);
			match = ucsdet_detect(det, &err);
			const char* encodeCharset = ucsdet_getName(match, &err);
			string encodeStr(encodeBuffer);

			cout << encodeStr << ": " << encodeCharset << endl;
		}
	}

	return 0;
}
